function daysJian(num){
    var date = new Date(num);//获取当前时间 
    var time = date.Format("yyyy-MM-dd hh:mm");
    return time;
}


$(".signout").on("click",function(){
    $.ajax({
        type:"post",
        url:"/api/user/signout",
        success:function(){
            window.location.href = "/signin";
        }
    });
});

//http://127.0.0.1:3000
var socket = io.connect("ws://");

var $box = 	$(".box");

var pageSize = 10;
var pageNum = 1;
var hasHistoryData = true;


var msgType = 5;  //1:对客服讲话,2:对人讲话,3:系统广播,4:大厅全局聊天5：机器人聊天

var messBase = {
    receive:"robot",
    username:userInfo.name,
    src:"",
    img:"",
    type:msgType,//1:对客服讲话,2:对人讲话,3:系统广播,4:大厅全局聊天5：机器人聊天
    msg:''
}

//正在链接
socket.on('connecting',function(){

});
//成功
socket.on('connect',function(){
    socket.emit('connectInit', messBase); //向服务器发送消息,告诉服务器，自己是谁
});

//链接失败
socket.on('connect_failed', function() {
    console.log("connect_failed");
});

//监听消息
socket.on('message',function(data){

    console.log("message",data);
    $box.append(createMessage(data));
    boxScrollTop();
});

//断开链接
socket.on('disconnect', function() {
    console.log("与服务其断开");
});

//重连
socket.on('reconnect', function() {
    console.log("重新连接到服务器");
});
socket.on('reconnect_failed', function() {
    console.log("重连失败");
});
socket.on('reconnecting', function() {
    console.log("正在重连");
});


//消息基本格式
/*	var messBase = {
 username:userInfo.name,
    receive:"1008客服",
    src:"",
    img:"",
    type:1,
    msg:''
}*/


$(".message").on("keyup",function (e) {

    if(e.keyCode == 13){
        $(".btn").click();
    }
})

$(".btn").on("click",function(){
    var msg = $(".message").val();
    msg = $.trim(msg);
    var mess = $.extend(true, {}, messBase);
    mess.msg = msg;
    socket.emit('message', mess);
    $(".message").val('');
});



function createMessage(obj){
    var str = "";
    var img = '';
    obj.icon = obj.icon || obj.username.substr(0,2) || '';

    if(obj.img || obj.src){
        var src = obj.img || obj.src;
        img = '<img src="'+ src +'" alt="" />'
    }

    if(obj.username == userInfo.name){
        str = '<div class="mess self">'+
            '<div class="icon">'+
            obj.icon +
            '</div>'+
            '<div class="info">'+
            '<p>'+
            '<span class="time">'+ daysJian(obj.time) +'</span>'+
            '<span class="name">'+
            obj.username +
            '</span>'+

            '</p>'+
            '<div class="mess-c">'+
            img+
            obj.msg +
            '</div>'+
            '</div>'+
            '</div>';
    }else{
        str = '<div class="mess">'+
            '<div class="icon">'+
            obj.icon +
            '</div>'+
            '<div class="info">'+
            '<p>'+

            '<span class="name">'+
            obj.username +
            '</span>'+
            '<span class="time">'+ daysJian(obj.time) +'</span>'+
            '</p>'+
            '<div class="mess-c">'+
            img+
            obj.msg +
            '</div>'+
            '</div>'+
            '</div>';
    }


    return str;
}

//滚动到底部
function boxScrollTop(){
    $box.scrollTop(100000);
}


//获取历史消息
function getHistory(toBottom,fellow,type){
    $.ajax({
        type:"post",
        url:"/api/message/history",
        data:{
            name:userInfo.name,
            type:type,
            fellow:fellow,
            pageSize:pageSize,
            pageNum:pageNum
        },
        success:function(ret){
            console.log(ret);
            var data = ret.data.list || [];
            for(var i = 0; i < data.length; i++){
                $box.prepend(createMessage(data[i]));
            }
            pageNum++;
            if(data.length == 0){
                hasHistoryData = false;
            }
            if(toBottom){
                boxScrollTop();
            }

        },
        error:function(error){
            console.log(error);
        }
    });
}

getHistory(true,messBase.receive,messBase.type);

//滚动到顶部，加载历史消息
$box.on('scroll',function(e){
    var $that = $(this);
    var scroll = $that.scrollTop();
    if(scroll <= 5 && hasHistoryData){
        getHistory(false,messBase.receive,messBase.type);
    }
});

//发送图片
$("#imgsend").on('change',function(){
    var that = this;
    var file = that.files[0];
    var mess = $.extend(true, {}, messBase);
    mess.msg = $(".message").val()
    console.log(file.name);
    var arr = file.name.split('.');
    var path = arr[arr.length-1].toUpperCase();
    var valid = ["JPG","JEPG","PNG","GIF"];
    if(valid.indexOf(path) == -1){
        return ;
    }
    html5Reader(file,function(img){
        mess.img = img;
        socket.emit('message', mess);
        $(".message").val('');
        that.value = '';
    });
    fileUpload(that.files,mess);
});
//转化为base64
function html5Reader(file,callback){
    var reader = new FileReader();

    reader.readAsDataURL(file);
    reader.onload = function(e){
        callback(this.result);
    }
}

//上传文件
function fileUpload(file,mess){
    var fd = new FormData($("#formUp")[0]);
    fd.append("username",mess.username);
    fd.append("receive",mess.receive);
    fd.append("type",mess.type);
    fd.append("msg",mess.msg);

    $.ajax({
        type:"post",
        url:"/api/fileup",
        type: 'POST',
        cache: false,
        data: fd,
        processData: false,
        contentType: false,
        success:function(data){
            console.log(data);
        },
        error:function(error){
            console.log(error)
        }
    });


}